package com.yj.suncity.activity.shouye;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.AdvDetailBean;
import com.yj.suncity.bean.ProductBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.zxing.CaptureActivity;
import com.yj.suncity.zxing.GenerateActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ProductDateilsActivity extends Activity implements OnClickListener {

	private static final int PAGER = 101;
	private Context context;
	private String goodId;
	private ViewPager pager;
	private LinearLayout lay_view_select;
	private int mWidth;
	private ViewPagerScroll pagerScroll;
	private int flag; // 1,抵购 2，兑换
	private Button mBtn_zixun,mBtn_buy;
	private List<Object> listPaths = new ArrayList<Object>();
	private TextView mTxt_goods_title, mTxt_goods_price, mTxt_goods_num,
			mTxt_surplus_num,mTxt_goods_info/*mTxt_silver_num,*/ /*mTxt_goods_address*/;
//	private TextView mTxt_silver_type;
	private TextView mTxt_silver_money;
	private TextView mTxt_address;
	private String mContent = "";

	private String userId;
	private String productUserId;
	private boolean isLogin;
	private boolean isShop;
	private boolean isCollect;
	private String collectType = "";
	private ImageView mImag_collect_normal, mImag_collect_press;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private TextView mTxt_shop_name, mTxt_shop_jianjie;
	private TextView mTxt_goumai, mTxt_peisong,
			mTxt_fukuan;// 联系
	private ImageView mImg_logo;
	private String mPhone = "";

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case PAGER:
				onResume();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_detail);
		context = this;
		mWidth = getResources().getDisplayMetrics().widthPixels;
		goodId = getIntent().getStringExtra("goodid");
		flag = getIntent().getIntExtra("flag", -1);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData();

	}

	private void initShopInfo(String shopUserId) {
		String path = URLCon.广告 + "?action=seeadvdetail&id=" + shopUserId;
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				final AdvDetailBean advDetailBean = new AdvDetailBean(json);
				imageLoader.displayImage(
						URLCon.HOST + advDetailBean.getEnt_logo(), mImg_logo,
						options);

				mTxt_shop_name.setText(advDetailBean.getEntname());
				mTxt_shop_jianjie.setText(advDetailBean.getEnt_jianjie());
				
				mPhone = advDetailBean.getEnt_contact_tel();
				
//				mTxt_contact_name.setText(advDetailBean.getEnt_contact());
//				mTxt_contact_phone.setText(advDetailBean.getEnt_contact_tel());
//				mTxt_contact_address.setText(advDetailBean.getEnt_address());
//				mTxt_contact_phone.setOnClickListener(new OnClickListener() {// 拨打电话
//							@Override
//							public void onClick(View v) {
//								DialogUtils dialogUtils = DialogUtils
//										.getInstance();
//								dialogUtils.CallDialog(context,
//										advDetailBean.getEnt_contact_tel());
//							}
//						});
			}
		});

	}

	private void findView() {
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		findViewById(R.id.lay_rela_goods_detail).setOnClickListener(this);
		mImag_collect_normal = (ImageView) findViewById(R.id.img_collet_normal);
		mImag_collect_press = (ImageView) findViewById(R.id.img_collet_press);
		mBtn_zixun = (Button) findViewById(R.id.buttion_zixun);
		mBtn_zixun.setOnClickListener(this);
		mBtn_buy = (Button) findViewById(R.id.btn_buy_goods);
		mBtn_buy.setOnClickListener(this);

//		mTxt_silver_type = (TextView) findViewById(R.id.txt_silver_type);
		mTxt_silver_money = (TextView) findViewById(R.id.txt_silver_money);
		mTxt_goods_info = (TextView)findViewById(R.id.goods_info_text);
//		mTxt_address = (TextView) findViewById(R.id.txt_address);

		mTxt_shop_name = (TextView) findViewById(R.id.txt_shop_name);
		mTxt_shop_jianjie = (TextView) findViewById(R.id.txt_shop_jianjie);
		mImg_logo = (ImageView) findViewById(R.id.img_logo);
		mTxt_goumai = (TextView) findViewById(R.id.txt_goumai);
		mTxt_peisong = (TextView) findViewById(R.id.txt_peisong);
		mTxt_fukuan = (TextView) findViewById(R.id.txt_fukuan);
//		if (flag == 1) {// 抵购
//			mBtn_duihuan_digou.setText("确定抵购");
//			mTxt_address.setText("低购地址：");
//			collectType = "5";
//		} else if (flag == 2) {// 兑换
//			mBtn_duihuan_digou.setText("确定兑换");
//			mTxt_address.setText("兑换地址：");
//			collectType = "6";
//		}
		lay_view_select = (LinearLayout) findViewById(R.id.lay_view_select);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay_view_page);
		layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth)));
		pager = (ViewPager) findViewById(R.id.view_pager);
		// ==========================================================================================

		mTxt_goods_title = (TextView) findViewById(R.id.txt_goods_title);
		mTxt_goods_price = (TextView) findViewById(R.id.txt_goods_price);
		mTxt_goods_num = (TextView) findViewById(R.id.txt_goods_num);
		mTxt_surplus_num = (TextView) findViewById(R.id.txt_surplus_num);
//		mTxt_silver_num = (TextView) findViewById(R.id.txt_silver_num);
//		mTxt_goods_address = (TextView) findViewById(R.id.txt_goods_address);

	}

	private void initData() {
		String path = URLCon.商品 + "?action=getgoods&id=" + goodId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......", new ResultCallBack() {

					@Override
					public void JSONResult(JSONObject jsonObject) {
						ProductBean productBean = new ProductBean(jsonObject);
						initShopInfo(productBean.getUser_id());

						if (productBean.getImg_url().contains(",")) {
							String[] string = productBean.getImg_url().split(
									",");
							for (String string2 : string) {
								listPaths.add(URLCon.HOST + string2);
							}
						} else {
							listPaths.add(URLCon.HOST
									+ productBean.getImg_url());
						}
						pagerScroll = new ViewPagerScroll(context, pager,
								lay_view_select, listPaths);

						Message message = new Message();
						message.what = PAGER;
						handler.sendMessage(message);
						mContent = productBean.getGoods_content();
						productUserId = productBean.getUser_id();
						mTxt_goods_title.setText(productBean.getGoods_title());
						mTxt_goods_price.setText("会员价：￥"
								+ productBean.getReal_price() + "元");
						mTxt_goods_num.setText(productBean.getGood_num() + "个");
						mTxt_surplus_num.setText("剩余："
								+ productBean.getSurplus_num() + "个");
//						mTxt_silver_num.setText(productBean.getSilver_num());
//						mTxt_goods_address.setText(productBean
//								.getGoods_address());
						mTxt_goods_info.setText(mContent);

						if (productBean.getGoods_price().equals("0")) {
//							mTxt_silver_type.setText("现金：");
							mTxt_silver_money.setText("店内价:");
							mTxt_silver_money.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
						} else {
//							mTxt_silver_type.setText("￥:");
							mTxt_silver_money.setText("店内价:"
									+ productBean.getGoods_price() + "元");
							mTxt_silver_money.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
						}
						if(productBean.getIs_delivery().equals("1")){
							mTxt_peisong.setText("支持本地配送");
						}else{
							mTxt_peisong.setText("不支持本地配送");
						}
						if(productBean.getIs_shoppurchase().equals("1")){
							mTxt_goumai.setText("支持店内购买");
						}else{
							mTxt_goumai.setText("不支持店内购买");
						}
						if(productBean.getDelivery_type().equals("1")){
							mTxt_fukuan.setText("免费配送");
						}else{
							mTxt_fukuan.setText("需要支付配送费用");
						}

					}
				});
		asyncTaskUtil.execute(path);
	}

	@Override
	protected void onResume() {
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		isShop = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.USERTYPE, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
			getCollectStatus();
		}
		if (pagerScroll != null) {
			pagerScroll.startTimer();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (pagerScroll != null) {
			pagerScroll.stopTimer();
		}
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
//		case R.id.lay_rela_goods_detail:
//			Intent intent = new Intent(this, ProductDetailWebActivity.class);
//			intent.putExtra("content", mContent);
//			startActivity(intent);
//			break;
		case R.id.lay_rela_collect:// 添加/移除收藏
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			if (isCollect) {
				removeCollect();
			} else {
				addCollect();
			}
			break;
//		case R.id.btn_ok:
//			if (!isLogin) {
//				startActivity(new Intent(context, LoginActivity.class));
//				return;
//			}
//			if (isShop && userId.equals(productUserId)) {
//				Intent intent2 = new Intent(context, CaptureActivity.class);
//				intent2.putExtra("flag", flag);
//				startActivity(intent2);
//				return;
//			}
//			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
//			pairs.add(new BasicNameValuePair("action", "addgoodsrecord"));
//			pairs.add(new BasicNameValuePair("userid", userId));
//			pairs.add(new BasicNameValuePair("goodsid", goodId));
//			String path = URLCon.兑换抵购;
//			Log.d("", path);
//			AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, pairs,
//					null, false, null, true, "", new ResultCallBack() {
//						@Override
//						public void JSONResult(JSONObject jsonObject) {
//							if (jsonObject.optString("success").equals("1")) {
//								Intent intent = new Intent(context,
//										GenerateActivity.class);
//								intent.putExtra("id",
//										jsonObject.optString("id"));
//								intent.putExtra("flag", flag);
//								startActivity(intent);
//							} else {
//								ToastUtil.ShowToast(context,
//										jsonObject.optString("msg"));
//							}
//						}
//					});
//			asyncTaskUtil.execute(path);
//			break;
		case R.id.buttion_zixun:
			DialogUtils dialogUtils = DialogUtils.getInstance();
			dialogUtils.CallDialog(context, mPhone);
			break;
		case R.id.btn_buy_goods:
			ToastUtil.ShowToast(context, "暂未开放......");
			break;
		}
	}

	private void addCollect() {
		String path = URLCon.收藏 + "?action=addcollection&userid=" + userId
				+ "&id=" + goodId + "&type=" + 8;
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "添加收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = true;
							mImag_collect_normal.setVisibility(View.GONE);
							mImag_collect_press.setVisibility(View.VISIBLE);
							ToastUtil.ShowToast(context, "收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getCollectStatus() {
		String path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
				+ "&id=" + goodId + "&type=" + 8;

		Log.d("", "获取收藏：" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				if (json.optString("success").equals("1")) {
					if (json.optString("state").equals("1")) {
						isCollect = true;
						mImag_collect_normal.setVisibility(View.GONE);
						mImag_collect_press.setVisibility(View.VISIBLE);
					} else {
						isCollect = false;
						mImag_collect_normal.setVisibility(View.VISIBLE);
						mImag_collect_press.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	private void removeCollect() {
		String path = URLCon.收藏 + "?action=delcollection&userid=" + userId
				+ "&id=" + goodId + "&type=" + 8;

		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "删除收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = false;
							setResult(1);
							mImag_collect_normal.setVisibility(View.VISIBLE);
							mImag_collect_press.setVisibility(View.GONE);
							ToastUtil.ShowToast(context, "删除收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

}
